package com.yuandengta.yomall.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.yuandengta.common.exception.BizCode;
import com.yuandengta.common.utils.R;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;

/**
 * Sentinel 配置 {@link SentinelConfig}
 *
 * @author Kevin
 * @email: 178676392@qq.com
 */
@Configuration
public class SentinelConfig {

    /**
     * GatewayCallbackManager注册回调进行异常定制
     */
    @PostConstruct
    private void initBlockHandler() {
        BlockRequestHandler blockRequestHandler = new BlockRequestHandler() {

            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
                R error = R.error(BizCode.TOO_MANY_REQUESTS.getCode(), BizCode.TOO_MANY_REQUESTS.getMessage());

                return ServerResponse.ok()
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(BodyInserters.fromValue(error));
            }
        };

        // GatewayCallbackManager注册回调进行异常定制
        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    }
}
